var ibMarketPluginBankManage = {
	init: function()
	{
		Debug.write("Initializing ibm.plugin.bank.manage.js");
		
		document.observe("dom:loaded", function(){
			$('bankAccountInfo').hide();
			$('transactions').hide();
			$('processResult').hide();
			
			ibMarketPluginBankManage.loadLinks();
			
			$('hideAccountInfo').observe('click', function() {
				ibMarketPluginBankManage.accountInfo = null;
				$('bankAccountInfo').hide();
				$('transactions').hide();
				$('processResult').hide();
			});
			$('withdrawAmount').observe('keyup', ibMarketPluginBankManage.updateWithdraw).writeAttribute('autocomplete', 'off');
			$('depositAmount').observe('keyup', ibMarketPluginBankManage.updateDeposit).writeAttribute('autocomplete', 'off');
			$('withdrawAmount').observe('focus', ibMarketPluginBankManage.updateWithdraw).observe('blur', function(){
				$('processResult').hide();
			});
			$('depositAmount').observe('focus', ibMarketPluginBankManage.updateDeposit).observe('blur', function(){
				$('processResult').hide();
			});
			
			ibMarketPluginBankManage.loadAccount(accountLoad);
		});
	},
	
	loadLinks: function()
	{
		$$('a.bankAccountLink').each(function(a)
		{
			var accountID = a.identify().sub('bankAccount_','');
			a.observe('click', function() {
				ibMarketPluginBankManage.loadAccount(accountID);
			});
		});
	},
	
	loadAccount: function(accountID)
	{
		if(!accountID)
		{
			return;
		}
		
		new Ajax.Request( ipb.vars['base_url'] + "app=ibmarket&module=ajax&plugin=bank&action=account&account_id=" + accountID + "&secure_key=" + ipb.vars['secure_hash'], 
							{
								method: 'get',
								evalJSON: 'force',
								onSuccess: function(t)
								{
									ibMarketPluginBankManage.accountInfo = null;
									if( Object.isUndefined( t.responseJSON ) )
									{
										Debug.error("Invalid server response");
										return false;
									}
									
									if( t.responseJSON['error'] )
									{
										Debug.error( t.responseJSON['error'] );
										return false;
									}
									
									ibMarketPluginBankManage.accountInfo = accountInfo = t.responseJSON;
									$('accountID').update(accountInfo['accountID']);
									$('accountName').update(accountInfo['a_name']);
									$('timeOpened').update(accountInfo['opened']);
									$('balance').update(accountInfo['currentBalance']);
									$('interestRate').update(accountInfo['interestRate']);
									$('interestTime').update(accountInfo['interestTime']);
									$('interestLast').update(accountInfo['interestLast']);
									$('withdrawFee').update(accountInfo['withdrawFee']);
									$('depositFee').update(accountInfo['depositFee']);
									$('removeFee').update(accountInfo['removeFee']);
									$('withdrawID').value = accountInfo['account_id'];
									$('depositID').value = accountInfo['account_id'];
									$('removeID').value = accountInfo['account_id'];
									$('withdrawAmount').value = 0;
									$('depositAmount').value = 0;
									$('bankAccountInfo').show();
									$('processResult').hide();
									
									while($('transactionsTable').rows.length > 2)
									{
										$('transactionsTable').deleteRow($('transactionsTable').rows.length - 2);
									}
									var c = 'row2';
									for(var i in accountInfo['transactions'])
									{
										if(isNaN(parseInt(i)))
										{
											continue;
										}
										var newRow = $('transactionsTable').insertRow($('transactionsTable').rows.length - 1).
														addClassName(c = (c == 'row1' ? 'row2' : 'row1'));
										newRow.insertCell(0).update(accountInfo['transactions'][i]['time']).addClassName('altrow');
										newRow.insertCell(1).update(accountInfo['transactions'][i]['transaction']);
										newRow.insertCell(2).update(accountInfo['transactions'][i]['amount']).addClassName('altrow');
										newRow.insertCell(3).update(accountInfo['transactions'][i]['fee']);
										newRow.insertCell(4).update(accountInfo['transactions'][i]['balance']).addClassName('altrow')	;
									}
									$('transactionsTable').rows[$('transactionsTable').rows.length - 1].removeClassName('row1')
														.removeClassName('row2').addClassName(c == 'row1' ? 'row2' : 'row1');
									$('transactionUrl').href = transaction_URL+accountInfo['account_id'];
									$('transactionUrl').href = $('transactionUrl').href.gsub('&amp;','&');
									$('transactions').show();
									
									return true;
								}
							});
	},
	
	updateWithdraw: function()
	{
		// No bank account loaded?
		if(!ibMarketPluginBankManage.accountInfo)
		{
			$('processResult').hide();
			return;
		}
		
		var amount = ibMarketFormatter.intval($F($('withdrawAmount')));
		if(amount <= 0)
		{
			$('processResult').hide();
			return;
		}
		
		var balance = parseInt(ibMarketPluginBankManage.accountInfo['balance']);
		var fee = parseFloat(ibMarketPluginBankManage.accountInfo['a_withdraw_fee']);
		var moneyFee = Math.round(amount * fee / 100);
		var newBalance = balance - amount;
		var newMoney = memberMoney + amount - fee;
		ibMarketPluginBankManage.updateResult('withdrawAmount', newBalance, newMoney);
	},
	
	updateDeposit: function()
	{
		// No bank account loaded?
		if(!ibMarketPluginBankManage.accountInfo)
		{
			$('processResult').hide();
			return;
		}
		
		var amount = ibMarketFormatter.intval($F($('depositAmount')));
		if(amount <= 0)
		{
			$('processResult').hide();
			return;
		}
		
		var balance = parseInt(ibMarketPluginBankManage.accountInfo['balance']);
		var fee = parseFloat(ibMarketPluginBankManage.accountInfo['a_deposit_fee']);
		var moneyFee = Math.round(amount * fee / 100);
		var newBalance = balance + amount;
		var newMoney = memberMoney - amount - fee;
		ibMarketPluginBankManage.updateResult('depositAmount', newBalance, newMoney);
	},
	
	updateResult: function(id, newBalance, newMoney)
	{
		$('processResult').show();
		$('new_balance').update(ibMarketFormatter.formatNumber(newBalance,true));
		$('new_money').update(ibMarketFormatter.formatNumber(newMoney,true));
		if(newBalance >= 0)
		{
			$('new_balance').setStyle({
				color: null
			});
		}
		else
		{
			$('new_balance').setStyle({
				color: 'red'
			});
		}
		if(newMoney >= 0)
		{
			// Good
			$('new_money').setStyle({
				color: null
			});
		}
		else
		{
			$('new_money').setStyle({
				color: 'red'
			});
		}
		var finalPos = {};
		
		// Position menu to keep it on screen
		var sourcePos = $(id).viewportOffset();
		var sourceDim = $(id).getDimensions();
		var delta = [0,0];
		var parent = null;
		var screenScroll = document.viewport.getScrollOffsets();
		
		if (Element.getStyle( $(id), 'position') == 'absolute')
		{
			parent = element.getOffsetParent();
			delta = parent.viewportOffset();
	    }
		
		finalPos['left'] = sourcePos[0] - delta[0];
		finalPos['top'] = sourcePos[1] - delta[1] + screenScroll.top;
		
		// Now try and keep it on screen
		finalPos['top'] = finalPos['top'] + sourceDim.height;
		
		$('processResult').setStyle('position: absolute; top: ' + finalPos['top'] + 'px; left: ' + finalPos['left'] + 'px; min-width: ' + $('withdrawAmount').getWidth() + 'px;');
	}
}

ibMarketPluginBankManage.init();